package com.snailhd.service;

import com.alibaba.fastjson.JSON;
import com.snailhd.common.entity.IResult;
import com.snailhd.common.util.DateUtils;
import com.snailhd.common.util.ScheduledThreadPoolManager;
import com.snailhd.common.util.ThreadPoolManager;
import com.snailhd.constant.MACD;
import com.snailhd.dto.QueryStockDayListDTO;
import com.snailhd.dto.QueryStockListDTO;
import com.snailhd.entity.Stock;
import com.snailhd.entity.StockDay;
import com.snailhd.mapper.StockDayMapper;
import com.snailhd.mapper.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 计算macd 并保存
 * @author hd
 * @date 2019-12-18 20:51
 */

@Slf4j
@Component
public class CalcMacdStockDayService {

    @Resource
    StockMapper stockMapper;

    @Resource
    StockDayMapper stockDayMapper;

    /**
     *
     * @param num 查询计算num天前开始以后的所有数据
     *
     */
    public IResult calcAndSave(Integer num){
        Date now = new Date();
        Integer start = DateUtils.formatDate2Int( DateUtils.addDay(now,-num) );
        Integer end  = DateUtils.formatDate2Int(now);

        List<Stock> stocks = stockMapper.query(new QueryStockListDTO());
        stocks.forEach(stock -> {
            ThreadPoolManager.getInstance().executeThread(new Runnable() {
                @Override
                public void run() {
                    log.info("计算mcad:{} --> {}",stock.getCode(),JSON.toJSONString(stock));
                    QueryStockDayListDTO query = QueryStockDayListDTO.builder()
                            .code(stock.getCode())
                            .start(start).end(end)
                            .order("code,date").build();
                    List<StockDay> stockDays = stockDayMapper.query(query);
                    if(stockDays.isEmpty()) { return;}
                    calc(stockDays);
                    stockDayMapper.updateMacd(stockDays);
                }
            });
        });
        return new IResult();
    }


    /**
     * 计算macd
     * @param stockDays 以时间排序的集合
     */
    private void calc(List<StockDay> stockDays){
        StockDay pre = null;
        for(StockDay stockDay:stockDays){
            if(BigDecimal.ZERO.compareTo(stockDay.getTrade())!=0){
                if(pre != null){
                    stockDay.calcMacd(pre);
                }
                pre = stockDay;
            }
        }
    }
}
